package com.panda.config;/**
 * @author 乐于吕
 * * @date 2024/10/22
 */

import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @Author: 乐于吕
 * @CreateTime: 2024-10-22
 * @Description:
 */

@Configuration
public class CustomerBeanConfig {

    @Bean
    public BlockExceptionHandler blockExceptionHandler() {

        return new BlockExceptionHandler() {
            @Override
            public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
                if (e instanceof FlowException) {
                    HashMap<String, Object> result = new HashMap<>();
                    result.put("code", 500);
                    result.put("message", "当前请求被流控");

                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter writer = httpServletResponse.getWriter();

                    String jsonStr = JSONUtil.toJsonStr(result);
                    writer.write(jsonStr);
                    writer.close();
                }
            }
        };

    }

}


